//
//  COSetViewController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit

class COSetViewController: COBaseController {
    
    let titleArr = [["Email","About us","Clear cache","Log out","Delete account"],
                     ["Terms of Service","Privacy Policy"]]

    lazy var containView: UIView = {
        let con = UIView()
        con.backgroundColor = .white
        return con
    }()
    
    lazy var baseTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            if #available(iOS 13.0, *) {
                tableView.automaticallyAdjustsScrollIndicatorInsets = false
            }else{
                tableView.contentInsetAdjustmentBehavior = .never
            }
        }else {
            automaticallyAdjustsScrollViewInsets = false
        }
        return tableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.baseTableView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addnav()
        self.title = "Setting"
        setUI()
    }
    
    // 设置UI
    func setUI(){
        self.view.addSubview(self.containView)
        self.containView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.navView.snp.bottom)
        }
        self.containView.addSubview(self.baseTableView)
        self.baseTableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.containView).offset(PTW(10))
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(30))
    }
}


extension COSetViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.titleArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.titleArr[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = COUserInfoManager.shared.curUser
        if (indexPath.section == 0 && indexPath.row == 0){
            let cell = COSetBindTabViewCell().cellWithTableView(tableView)
            cell.selectionStyle = .none
            let email = model?.userResponse.email
            if(email?.isEmptyStr == false){
                cell.rightLbl.text = email
                cell.rightLbl.textColor = UIColor.colorWithHex("#FF4D95",1)
                cell.freeImg.isHidden = true
            }else{
                cell.rightLbl.text = "verify email"
                cell.rightLbl.textColor = UIColor.colorWithHex("#7863A6", 0.5)
                let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
                let alreadyCalled = kIsAllreadyCalled.keyGetNSDefaultsKey() as? Bool
                if (feed == false  && alreadyCalled == true){
                    cell.freeImg.isHidden = false
                }else{
                    cell.freeImg.isHidden = true
                }
            }
            return cell
        }else{
            let cell = COEditProfileViewCell().cellWithTableView(tableView)
            cell.selectionStyle = .none
            cell.leftLbl.text = self.titleArr[indexPath.section][indexPath.row]
            cell.rightLbl.text = ""
            if (indexPath.section == 0){
                if (indexPath.row == 0){
                }else if (indexPath.row == 1){
                    cell.rightLbl.text = "version\(KBundleVersion)"
                    cell.iconImg.isHidden = true
                    cell.rightLbl.textColor = UIColor.colorWithHex("#7863A6",0.5)
//                    cell.rigntArrow.isHidden = true
                }else if (indexPath.row == 2){
                    // clear cache
                    KingfisherManager.shared.cache.calculateDiskStorageSize { (results) in
                        let string =  results.map({ String($0) })
                        do {
                            let value = try string.get()
                            let num =   (Double(value) ?? 0.0) / 1000.0 / 1000.0
                            if num > 0{
                                cell.rightLbl.text = String(format: "%.2fM", num)
                            }else{
                                cell.rightLbl.text = "0M"
                            }
                            cell.rightLbl.textColor = UIColor.colorWithHex("#FF4D95",1)
                        }catch{
                            print("\(error)")
                        }
                    }
                }else if (indexPath.row == 4){
                    cell.bottomLine.isHidden = true
                }
            }else{
                if (indexPath.row == 1){
                    cell.bottomLine.isHidden = true
                }
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if(indexPath.section == 0 && indexPath.row == 0){
            return PTW(100)
        }else{
            return PTW(80)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if(section == 0){
            return 0.01
        }else{
            return 10
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if(section == 0){
            return UIView()
        }else{
            let foot = UIView(frame: CGRectMake(0, 0, SCREENWIDTH, 10))
            foot.backgroundColor = .clear
            return foot
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = COUserInfoManager.shared.curUser
        if (indexPath.section == 0){
            if (indexPath.row == 0){
                let email = model?.userResponse.email
                if(email?.isEmptyStr == true){
                    let bindEmail = COBindEmailController()
                    bindEmail.hidesBottomBarWhenPushed = true
                    let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
                    let isalready = kIsAllreadyCalled.keyGetNSDefaultsKey() as? Bool
                    if(feed == false && isalready == true){
                        bindEmail.type = 1
                    }
                    self.navigationController?.pushViewController(bindEmail, animated: true)
                }else{
                    UIToolHelper.makeToast("You've already tied your email.")
                }
            }else if (indexPath.row == 2){
                UIToolHelper.makeToast("Cleaning...")
                KingfisherManager.shared.cache.clearDiskCache {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                        self.baseTableView.reloadData()
                    }
                }
            }else if (indexPath.row == 3){
                self.showAlert(style: .actionSheet, title: "", message: "Are you sure to logout?", actions: ["Confirm"]) { type in
                    self.logoutMyAccount()
                }
            }else if (indexPath.row == 4){
                self.showAlert(style: .actionSheet, title: "Are you sure to delete your account?", message: "After being deleted, data will be permanently deleted.", actions: ["Confirm"]) { type in
                    self.deleteMyAccount()
                }
            }
        }else{
            if (indexPath.row == 0){
                let url = KTerms
                let vc = COWebViewController(url)
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                let url = KPolicy
                let vc = COWebViewController(url)
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    // 删除账号
    func deleteMyAccount(){
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.deleteAccount, modelType: CONSObjectModel.self) { code, object, success in
            UIToolHelper.hideHUD()
            COUserInfoManager.coClearInfo()
            KAppDelegate.setRootViewController()
            NotificationCenter.default.post(name: .QuitAppTimeStopNotification, object: nil)
            kIsAllreadyCalled.keySaveToNSDefaults(with: false)
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
        }
    }
    
    // 退出账号
    func logoutMyAccount(){
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.logoutAccount, modelType: CONSObjectModel.self) { code, object, success in
            UIToolHelper.hideHUD()
            COUserInfoManager.coClearInfo()
            KAppDelegate.setRootViewController()
            NotificationCenter.default.post(name: .QuitAppTimeStopNotification, object: nil)
            kIsAllreadyCalled.keySaveToNSDefaults(with: false)
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
        }
    }
}
